package com.ymttest.database.mongo;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import com.ymttest.database.model.mongo.query.UserIndex;
import com.ymttest.database.mongo.config.MongoUserConfig;
import com.ymttest.database.mongo.config.SchemaField;
import com.ymttest.database.mongo.config.UserIndexField;


/**
 * Created by zhangzhiqiang on 2016/12/27.
 */
@Repository
public class UserIndexQueryWapper {

    private MongoTemplate mongoUserTemplate;
    
    public UserIndexQueryWapper(){
    	try {
    		mongoUserTemplate = new MongoUserConfig().mongoSellerTemplate();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

    private String getCollectionName(long userId) {
        long n = userId % 100;
        return SchemaField.USER + n;
    }

    public <T> List<T> find(Query query, Integer userId, Class<T> outputType) {
        return mongoUserTemplate.find(query, outputType, getCollectionName(userId));
    }

    public <T> List<T> aggregate(long userId, Aggregation aggregation, Class<T> outputType) {

        return mongoUserTemplate.aggregate(aggregation, getCollectionName(userId), outputType).getMappedResults();
    }

    public UserIndex findById(long orderId, long userId) {

        return mongoUserTemplate.findById(orderId, UserIndex.class, getCollectionName(userId));
    }

    public boolean exists(Query query, long userId) {
        return mongoUserTemplate.exists(query, getCollectionName(userId));
    }

    public long count(Query query, long userId) {
        return mongoUserTemplate.count(query, getCollectionName(userId));
    }

    public List<Long> queryOrderId(Query query, long userId) {
        query.fields().include(UserIndexField.ID);
        List<UserIndex> userIndexs = mongoUserTemplate.find(query, UserIndex.class, getCollectionName(userId));
        return userIndexs.stream().map(e -> e.getId()).collect(Collectors.toList());
    }

    public UserIndex findByIdWithQuery(Query query,long orderId,long userId){
        query.fields().include(UserIndexField.ID);
        query.addCriteria(Criteria.where(UserIndexField.ID).is(orderId));
        return mongoUserTemplate.findOne(query,UserIndex.class, getCollectionName(userId));
    }
}
